package com.example.springmysqldemo.controller;

import com.example.springmysqldemo.dao.DepartmentDao;
import com.example.springmysqldemo.dao.UserDao;
import com.example.springmysqldemo.entity.Department;
import com.example.springmysqldemo.entity.User;
import com.example.springmysqldemo.result.Result;
import com.example.springmysqldemo.service.DeptService;
import com.example.springmysqldemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@CrossOrigin
@RequestMapping("/api")
public class LoginController {
    @Autowired
    UserService userService;
    @Autowired
    DeptService deptService;


    @CrossOrigin
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody User user){
        String username = user.getUsername();
        String password = user.getPassword();
        // 获取数据库中账号密码
        List<User> allUsers = userService.findAllUsers();
        for (User u:allUsers){
            if (u.getUsername().equals(username) && u.getPassword().equals(password)){
                // 获取id信息
                User loginuser = userService.UserInfo(username,password);
                user.setToken(loginuser.getToken());
                user.setId(loginuser.getId());
                // 获取部门的信息
                Department dept = deptService.DeptInfo(loginuser.getId());
                user.setDepartment(dept);
                System.out.println("密码正确");
                return new Result(200,"登录成功",user);
            }
        }
        System.out.println("密码错误");
        return new Result(400,"登录失败",user);
    }
}
